package com.m.system.service.impl;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.m.system.domain.SysRoleEntity;
import com.m.system.domain.SysRoleMenuEntity;
import com.m.system.mapper.SysRoleMapper;
import com.m.system.mapper.SysRoleMenuMapper;
import com.m.system.service.SysRoleService;
import com.m.utils.IdUtil;


import org.springframework.beans.factory.annotation.Autowired;

/**
 * 角色信息表Service
 * 
 * @author monxz
 * @version 2021-01-29
 */
@Service
@Transactional
public class SysRoleServiceImpl implements SysRoleService {

	@Autowired
	private SysRoleMapper sysRoleMapper;

	@Autowired
	private SysRoleMenuMapper roleMenuMapper;

	@Override
	public List<SysRoleEntity> findSysRoleList(SysRoleEntity sysRoleEntity) throws Exception {
		
		return sysRoleMapper.getList(sysRoleEntity);
	}

	@Override
	public Integer addSysRole(SysRoleEntity sysRoleEntity) throws Exception {
		sysRoleEntity.setRoleId(IdUtil.genId());
		if (!sysRoleEntity.getMenuIds().isEmpty()) {
			List<SysRoleMenuEntity> srList = new ArrayList<SysRoleMenuEntity>();
			for (String menuId : sysRoleEntity.getMenuIds()) {
				srList.add(new SysRoleMenuEntity(sysRoleEntity.getRoleId(), menuId));
			}
			roleMenuMapper.insertRoleMenu(srList);
		}
		return sysRoleMapper.insert(sysRoleEntity);
	}

	@Override
	public Integer modifySysRole(SysRoleEntity sysRoleEntity) throws Exception {
		roleMenuMapper.deleteRoleMenuIds(sysRoleEntity.getRoleId());
		if (!sysRoleEntity.getMenuIds().isEmpty()) {
			List<SysRoleMenuEntity> srList = new ArrayList<SysRoleMenuEntity>();
			for (String menuId : sysRoleEntity.getMenuIds()) {
				srList.add(new SysRoleMenuEntity(sysRoleEntity.getRoleId(), menuId));
			}
			roleMenuMapper.insertRoleMenu(srList);
		}
		return sysRoleMapper.update(sysRoleEntity);
	}

	@Override
	public Integer delete(SysRoleEntity sysRoleEntity) throws Exception {
		roleMenuMapper.deleteByRoleIds(Arrays.asList(sysRoleEntity.getRoleId()));
		return sysRoleMapper.delete(sysRoleEntity);
	}

	@Override
	public Integer deleteFalse(String ids) throws Exception {
		roleMenuMapper.deleteByRoleIds(Arrays.asList(ids.replaceAll("\"", "").split(",")));
		return sysRoleMapper.deleteFalse(ids.replaceAll("\"", "").split(","));
	}

	@Override
	public Integer checkUnion(SysRoleEntity sysRoleEntity) throws Exception {
		String roleId = sysRoleEntity.getRoleId();
		sysRoleEntity.setRoleId(null);
		List<SysRoleEntity> sysRoleList = sysRoleMapper.getExctList(sysRoleEntity);
		if (sysRoleList == null || sysRoleList.isEmpty()) {
			return 0;
		}
		if (roleId != null && sysRoleList.size() == 1 && roleId.equals(sysRoleList.get(0).getRoleId())) {
			return 0;
		}

		return 1;

	}

}